from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, reqparse, inputs, abort, marshal, fields
from sqlalchemy import or_

from apps.models.moey_model import WalletMoney
from apps.models.user_model import User
from apps.utils.decorator import login_required
from apps.utils.token_util import generator_token
from exts import redis_cache, db

user_bp = Blueprint('user', __name__, url_prefix='/user')

api = Api(user_bp)

# action= login | register
parser = reqparse.RequestParser()
parser.add_argument('action', type=str, required=True, help='必须输入操作类型')
parser.add_argument('password', type=inputs.regex(r'^[a-zA-Z]\w{5,15}$'), required=True, help='必须输入密码')

# 注册
register_parser = parser.copy()
register_parser.add_argument('username', type=str, required=True, help='必须输入用户名')
register_parser.add_argument('email', type=str, required=True, help='必须输入邮箱')
register_parser.add_argument('repassword', type=inputs.regex(r'^[a-zA-Z]\w{5,15}$'), required=True, help='必须输入确认密码')
register_parser.add_argument('phone', type=inputs.regex(r'^1[35789]\d{9}$'), help="手机号码格式错误")

# 登录
login_parser = parser.copy()
login_parser.add_argument('username', type=str, help='必须输入用户名')
login_parser.add_argument('email', type=str, help='必须输入邮箱')

# 改密
change_parser = reqparse.RequestParser()
change_parser.add_argument('old_password', type=inputs.regex(r'^[a-zA-Z]\w{5,15}$'), required=True, help='必须输入旧密码')
change_parser.add_argument('new_password', type=inputs.regex(r'^[a-zA-Z]\w{5,15}$'), required=True, help='必须输入旧密码')

# 格式化用户输出规则
user_fileds = {
    'username': fields.String,
    'phone': fields.String,
    'email': fields.String
}
maney_fileds = {
    # 钱币A
    'moneyA': fields.Float,
    # 钱币A
    'moneyB': fields.Float,
    # 钱包地址
    'money_localtion': fields.String,
    # 外键
    # 'user_id': fields.String
}
password_fileds = {
    'password': fields.String
}

# maney = WalletMoney()
# maney.moneyA = 0
# maney.moneyB = 0
# maney.money_localtion = generator_token()
# maney.user_id = user.id


class UserResource(Resource):

    def post(self):
        args = parser.parse_args()
        action = args.get('action')
        password = args.get('password')

        # 注册
        if action == 'register':
            register_args = register_parser.parse_args()
            username = register_args.get('username')
            repassword = register_args.get('repassword')
            email = register_args.get('email')
            phone = register_args.get('phone')
            if password == repassword:
                user = User()
                user.username = username
                user.email = email
                user.password = password
                if phone:
                    user.phone = phone

                flag = user.save()
                if flag:
                    money = WalletMoney()
                    money.user_id = user.id
                    money.moneyA = 0.0
                    money.moneyB = 0.0
                    # 钱包地址
                    money.money_localtion = generator_token()

                    db.session.add(money)
                    db.session.commit()
                    data = {
                        'status': 200,
                        'msg': '注册成功',
                        'user': marshal(user, user_fileds),
                        'maney': marshal(money, maney_fileds)
                    }
                    return jsonify(data)
                else:
                    abort(400, msg='注册失败')
            else:
                abort(400, msg='两次密码不一致')

        # 登录
        elif action == 'login':
            login_args = login_parser.parse_args()
            login_name = login_args.get('username') or login_args.get('email')
            if not login_name:
                abort(400, msg='请输入用户名或者邮箱')
            user = User.query.filter(or_(User.username == login_name, User.email == login_name)).first()
            if user and user.check_password(password):
                # 用户登录成功
                # 1. 产生令牌token
                token = generator_token()
                # 2. redis进行缓存保存
                redis_cache.set(token, user.id, timeout=60 * 60)
                # print("-----------------------------------------")

                data = {
                    'status': 200,
                    'msg': '登录成功',
                    'token': token
                }
                return jsonify(data)
            else:
                abort(400, msg='用户名或者密码有误')


class Gaimi(Resource):
    @login_required
    def post(self):
        user = g.user

        if user:
            register_args = change_parser.parse_args()
            old_password = register_args.get('old_password')
            new_password = register_args.get('new_password')
            print(user.check_password(old_password))
            if user.check_password(old_password):
                user.password = new_password
                db.session.add(user)
                db.session.commit()
                data = {
                    'status': 200,
                    'msg': '密码修改成功'
                }
                return jsonify(data)
            else:
                abort(400,msg='旧密码输入错误')



api.add_resource(Gaimi, '/g/')
api.add_resource(UserResource, '/')
# api.add_resource(OrderResource, '/order/')
# api.add_resource(Money, '/money/')
